import numpy as np
from sklearn import linear_model
from sklearn.preprocessing import StandardScaler


def linear_regression_by_sklearn(x, y):
    """
    通过 Scikit-learn 库实现线性回归 (n 个特征数据, 1 个目标值)

    :param x: 特征数据
    :param y: 目标值
    """
    # 标准化
    scaler = StandardScaler()
    scaler.fit(x)
    x_train = scaler.transform(x)
    x_test = scaler.transform(np.array([1650, 3]).reshape(1, -1))

    # 线性模型拟合
    model = linear_model.LinearRegression()
    model.fit(x_train, y)

    # 结果预测
    result = model.predict(x_test)
    print(f"特征系数: {model.coef_}")  # 特征系数
    print(f"偏置: {model.intercept_}")  # 偏置(截距)
    print(f"预测结果: {result}")  # 预测结果


if __name__ == "__main__":
    data = np.loadtxt("data.txt", delimiter=",")
    x_data = np.array(data[:, 0:-1])
    y_data = np.array(data[:, -1])

    linear_regression_by_sklearn(x_data, y_data)
